<template>
  <div class="app-container">
    <el-card>
      <!--      <div slot="header" class="clearfix">-->
      <!--        <span>基本设置</span>-->
      <!--      </div>-->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="首页轮播图" name="scenicInfo">
          <ul class="image-upload">
            <draggable v-model="imageListArr" :animation="200" @update="dataDragEnd">
              <!--过渡动画-->
              <transition-group>
                <li v-for="(item, index) of imageListArr" :key="item.url">
                  <el-image v-if="item.url" :src="item.url" title="按住可拖拽排序"/>
                  <div class="icon-container">
                  <span v-if="item.url" @click="handleRemoveByIndex(index_1)">
                    <i class="el-icon-delete" style="margin-right:15px"></i>
                  </span>
                    <span v-if="item.url" class="el-upload-list__item-preview" @click="handlePreviewByIndex(index_1)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  </div>
                  <!--                  <div style="text-align: center;font-size: 13px;margin-top: 5px">-->
                  <!--                    <span>{{ item.name }}</span>-->
                  <!--                  </div>-->
                </li>
              </transition-group>
            </draggable>
            <el-upload
              v-if="true"
              ref="upload"
              class="upload-demo"
              action="#"
              accept=".jpg,.jpeg,.png"
              :file-list="fileList"
              list-type="picture-card"
              :show-file-list="false"
              :auto-upload="false"
              :limit="5"
              :on-exceed="fileSizeExceed"
              :on-change="onChange"
              :before-upload="beforeUpload"
              :http-request="handleUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <!--            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
              <!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
            </el-upload>
          </ul>

          <el-button style="margin-left: 5px;margin-top: 15px" size="small" type="success" @click="submitUpload">
            提交保存
          </el-button>
          <div style="margin-top: 40px">
            <span style="font-size: 15px;font-weight: 700">提示：</span>
            <ul style="font-size: 14px;margin-left: 8px">
              <li>1, 只能上传jpg/png格式的图片，且大小不能超过5MB;</li>
              <li>2, 最多只允许上传5张图片;</li>
            </ul>
          </div>
        </el-tab-pane>
        <el-tab-pane label="文档资源" name="operationTimeSetting">
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import oss from "@/utils/oss"
import draggable from 'vuedraggable';

export default {
  name: "Resource",
  components: {draggable},
  data() {
    return {
      activeTab: "scenicInfo", //景区基本信息
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      imageListArr: [],
    }
  },
  mounted() {
    this.getSlidePictureList()
  },
  methods: {
    getFileSuffixName(name) {
      return name.substring(name.lastIndexOf("."));//.txt
    },
    getFileNameUUID() {
      function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }

      return `${+new Date()}_${rx()}${rx()}`
    },
    beforeUpload(file) {
      // 限制上传类型
      // const fileExtensions = this.getFileName(file.name) === '.doc' || this.getFileName(file.name) === '.docx' || this.getFileName(file.name) === '.pdf'
      const fileExtensions = this.getFileSuffixName(file.name) === '.jpg' || this.getFileSuffixName(file.name) === '.png'
      //限制的上限为10M
      const max20M = file.size / 1024 / 1024 < 5;
      if (!fileExtensions) {
        // this.$message.error('上传文件类型只能是 .doc, .docx, .pdf 格式!');
        this.$message.error('只能上传.jpg, .png格式的图片!');
      }
      if (!max20M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return fileExtensions && max20M;
    },
    handleUpload(option) {
      console.log("handleUpload option: ", option)
      let originFileName = option.file.name;
      // this.imageListArr.
      // 生成的文件名，保留文件后缀名，进行拼接
      let fileName = this.getFileNameUUID() + this.getFileSuffixName(option.file.name)

      //同步上传
      // oss.putSync(`slidePictures/${fileName}`, option.file);
      //异步上传
      oss.put(`slidePictures/${fileName}`, option.file).then(res => {
        this.$message.success('上传成功!');
        this.getSlidePictureList();
      }).catch(err => {
        this.$message.error('上传失败!');
      });
    },
    handleRemove(file, imageListArr) {
      console.log(file, imageListArr);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    submitUpload() {
      if (this.imageListArr.length > 5) {
        this.$message.error("最多只允许上传5张图片!")
        return
      }
      // this.$refs.upload.submit();
      //先删除oss服务器中slidePictures/路径下的所有轮播图
      let imageNameArr = []
      for (let i = 1; i <= 5; i++) {
        imageNameArr.push("slidePictures/" + i + ".jpg")
        imageNameArr.push("slidePictures/" + i + ".png")
      }
      oss.deleteMulti(imageNameArr).then(res => {
        console.log("submitUpload res: ", res)
        // this.getSlidePictureList();
        //将所有文件重新上传
        oss.batchPut(this.imageListArr).then(res => {
          console.log("submitUpload batchPut res: ", res)
          this.$message.success("上传成功！")
        }).catch(err => {
          console.log("submitUpload batchPut err: ", err)
          this.$message.error("上传失败！")
          oss.deleteMulti(imageNameArr)
        })
      }).catch(err => {
        console.log("submitUpload err: ", err)
      })

    },
    fileSizeExceed() {
      this.$message.error('最多只允许上传5张图片 !');
    },
    //获取轮播图列表
    getSlidePictureList() {
      oss.listDir("slidePictures/").then(res => {
        console.log("mounted listDir res= ", res)
        if (res.objects || res.objects.length > 0) {
          this.imageListArr = [];
          res.objects.forEach((item, index) => {
            // debugger
            let sortStr = item.name.substring(item.name.lastIndexOf("/") + 1, item.name.lastIndexOf("."))
            this.imageListArr[parseInt(sortStr) - 1] = {
              name: item.name.substring(item.name.lastIndexOf("/") + 1),
              url: oss.signatureUrl(item.name),
              sortNum: parseInt(sortStr)
            }
          })
        }
        // debugger
      }).catch(err => {
        console.log("mounted listDir err= ", err)
      });
    },
    //拖拽图片
    dataDragEnd() {
      // 拖拽结束后给imageListArr中所有元素的sortNum重新排序
      this.imageListArr.forEach((item, index) => {
        item.sortNum = index_1 + 1
      })
      //过滤一下url为空的数据
      this.imageListArr = this.imageListArr.filter(item => {
        return item.url != ''
      });
    },
    handleRemoveByIndex(index) {
      let imgFile = this.imageListArr[index_1];
      this.imageListArr.splice(index_1, 1)
      //此处不要直接就去删除oss中的文件
      // oss.deleteOne(`slidePictures/${imgFile.name}`).then(res => {
      //   this.$message.success("删除成功！")
      //   this.getSlidePictureList();
      // }).catch(err => {
      //   this.$message.error("删除失败！")
      // })
    },
    //处理图片预览效果
    handlePreviewByIndex(index) {
      this.dialogImageUrl = this.imageListArr[index_1].url;
      this.dialogVisible = true;
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    onChange(file, fileList) {
      console.log("onChange: ", file, fileList)

      if (file.status === "ready") { //此为添加的图片
        if (this.imageListArr.length >= 5) {
          this.$message.error('最多只允许上传5张图片 !');
          return
        }
        this.imageListArr.push({
          name: (this.imageListArr.length + 1) + this.getFileSuffixName(file.name),
          url: file.url,
          sortNum: this.imageListArr.length + 1,
          raw: file.raw
        })
      }
    }
  }
}
</script>

<style scoped>

.image-upload {
  list-style-type: none;
  display: flex;
}

.image-upload li {
  display: inline-block;
  margin: 10px;
}

.image-upload i:hover {
  cursor: pointer;
}

.image-upload .el-image {
  width: 146px;
  height: 146px;
  border-radius: 6px;
}

.image-upload .el-image:hover {
  cursor: pointer;
}

>>> .image-upload .el-upload {
  margin-top: 10px;
  margin-left: 10px;
}

</style>
